package br.com.maternity.servlets;

import br.com.maternity.classes.dao.MedicoDAO;
import br.com.maternity.classes.dao.UsuarioDAO;
import br.com.maternity.classes.entity.Medico;
import br.com.maternity.classes.entity.Usuario;
import br.com.maternity.util.Parser;
import br.com.maternity.util.Validator;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Gattini
 */
@WebServlet(name = "cadastroMedico", urlPatterns = {"/cadastroMedico"})
public class cadastroMedico extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        boolean isNovo = Parser.parseString(request.getParameter("hdfId")).isEmpty();
        String crm = Parser.parseString(request.getParameter("txtCRM"));
        String cpf = Parser.parseString(request.getParameter("txtCPF"));
        String nome = Parser.parseString(request.getParameter("txtNome"));
        String telefone = Parser.parseString(request.getParameter("txtTelefone"));
        String senha = Parser.parseString(request.getParameter("txtSenha"));

        MedicoDAO dao = null;

        String msg = "";
        if (crm.trim().equals("")) {
            msg += "CRM invalido. ";
        } else {
            //CASO NÃO SEJA EDIÇÃO, VALIDA SE JÁ EXISTE O CRM INFORMADO
            if (isNovo) {
                dao = new MedicoDAO();
                Medico old = dao.getByCrm(Integer.parseInt(crm));
                if (old != null) {
                    msg += "CRM ja cadastrado para o medico " + old.getNome() + ". ";
                }
            }
        }

        if (cpf.trim().equals("")) {
            msg += "CPF invalido. ";
        } else {
            if (!Validator.isCpf(cpf)) {
                msg += "CPF invalido. ";
            } else {
                if (isNovo) {
                    dao = new MedicoDAO();
                    Medico old = dao.getByCpf(cpf);
                    if (old != null) {
                        msg += "CPF ja cadastrado para o medico " + old.getNome() + ". ";
                    }
                }
            }
        }

        if (nome.trim().equals("")) {
            msg += "Nome invalido. ";
        }

        if (senha.trim().equals("")) {
            msg += "Senha invalida. ";
        }

        response.setContentType("text/html;charset=UTF-8");

        if (!msg.equals("")) {
            response.getWriter().write("0|" + msg);
        } else {
            if (dao == null) {
                dao = new MedicoDAO();
            }

            Medico m;
            if (isNovo) {
                m = new Medico();
                m.setCrm(Integer.parseInt(crm));
            } else {
                m = dao.getByCrm(Integer.parseInt(crm));
            }

            m.setCpf(cpf);
            m.setNome(nome);
            m.setTelefone(telefone);
            if (dao == null) {
                dao = new MedicoDAO();
            }

            if (isNovo) {
                if (dao.insert(m)) {
                    Usuario u = new Usuario();
                    u.setLogin(crm.toString());
                    u.setSenha(senha);
                    u.setTipo(2);
                    UsuarioDAO daoUser = new UsuarioDAO();
                    daoUser.insert(u);
                }

            } else {
                if (dao.update(m) == 1) {
                    UsuarioDAO daoUser = new UsuarioDAO();
                    Usuario u = daoUser.getByLoginTipo(crm, 2);
                    if (u != null) {
                        u.setSenha(senha);
                        daoUser.update(u);
                    }
                }
            }

            response.getWriter().write("1|" + request.getContextPath() + "/relatorios/listagemMedicos.jsp");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
